package com.itheima.interceptor;

import com.aliyuncs.utils.StringUtils;
import com.itheima.utils.JwtUtils;
import com.itheima.utils.ThreadLocalUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.HandlerInterceptor;
@Slf4j
@Component
@Transactional(rollbackFor = Exception.class)
public class TokenIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("token");
        if(StringUtils.isEmpty( token)){
            //返回401
            response.setStatus(401);
            //不放行
            return false;
        }

        //解析token
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Object id = claims.get("id");
            //把id存到ThreadLocal中
            ThreadLocalUtils.set(Integer.parseInt(id.toString()));
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败");
            //返回401
            response.setStatus(401);
            return false;
        }

        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtils.remove();
    }
}
